﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace AbpDemo.HttpApi.Host
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class RealIpMiddleware
    {
        private readonly RequestDelegate _next;

        public RealIpMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {
            var headers = httpContext.Request.Headers;
            if (headers.ContainsKey("X-Forwarded-For"))
            {
                httpContext.Connection.RemoteIpAddress = IPAddress.Parse(headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0]);
            }
            return _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class RealIpMiddlewareExtensions
    {
        public static IApplicationBuilder UseRealIpMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RealIpMiddleware>();
        }
    }
}
